<template>
<!-- Main content -->
<div>
    <div class="row">
        <div class="col-xs-12">
            <theme-box title="文章列表">
                <form class="form-inline" @submit.prevent v-el:form>
                    <form-select title="商户号" :up-table="true" :sreach="true" name="mchtId" :options="mchtList"></form-select>
                    <form-date-time title="开始时间" :up-table="true" name="beginDate"></form-date-time>
                    <form-date-time title="结束时间" :up-table="true" name="endDate"></form-date-time>

                    <span class="pull-right">
                        <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                    <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                    </span>

                </form>
                <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                </table>
            </theme-box>
        </div>
        <!-- /.col -->
    </div>
    <modal-container title="修改" v-el:revise-modal v-ref:revise-modal class="edit-modal">
        <form @submit.prevent @reset.prevent v-el:revise-mform>
            <div class="modal-body">
                <table-modal :item="item" :columns-set="columnsReviseSet" :columns-num="1" :checkbox-value.sync="checkboxValue" ></table-modal>
                <div class="alert alert-default" v-show="htmlEdit">
                    <td><span class="required">&nbsp;&nbsp;*</span>文章内容</td>
                    <html-edit :content.sync="htmlContent" height="100" v-ref:note></html-edit>
                </div>
            </div>

        </form>

        <div class="modal-footer">
            <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
            <v-button theme="primary" type="submit" @click="sumbit">保存</v-button>
        </div>

    </modal-container>

    <modal-container title="详情" v-el:detail-modal v-ref:detail-modal class="edit-modal">
        <form @submit.prevent @reset.prevent v-el:detail-mform>
            <div class="modal-body">
                <table class="table table-bordered table-hover">
                    <!--<tr>-->
                    <!--<td style="width:50%">商户号</td>-->
                    <!--<td>{{item.mchtId}}</td>-->
                    <!--</tr>-->
                    <tr>
                        <td style="width:50%">文章号</td>
                        <td>{{item.docId}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">文章标题</td>
                        <td>{{item.docTitle}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">文章封面</td>
                        <td><img class="table-avatar" :src="item.picUrl" style="width:30%"></td>
                    </tr>
                    <tr>
                        <td style="width:50%">发现类型</td>
                        <td>{{item.docType}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">文章内容</td>
                        <td style="word-wrap:break-word;word-break:break-all;" name="myTd" id="myTd"></td>
                    </tr>
                    <tr>
                        <td style="width:50%">文章作者</td>
                        <td>{{item.docAuthor}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">文章描述</td>
                        <td style="word-wrap:break-word;word-break:break-all;">{{item.docDesc}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">相关状态</td>
                        <td>{{item.state == "0" ? "正常":"关闭"}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">访问总数</td>
                        <td>{{item.visitCount}}</td>
                    </tr>
                    <tr>
                        <td style="width:50%">创建时间</td>
                        <td>{{item.mcreTime}}</td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
            </div>
        </form>
    </modal-container>
    <!-- /.row -->
</div>
<!-- /.content -->
</template>

<style lang="less" scoped>
.form-inline .btn+.btn {
    margin-right: 10px;
}
</style>
<script>
//解决datatables弹窗警告
$.fn.dataTable.ext.errMode = 'none';
import summernote from "pages/partial/summernote.vue";
import {
    dateTime,
    createDataTable
} from 'ui/collections/general.js';
var serialize = require('form-serialize');
import {
    dateFormat
} from "lib/method.js"

var dataTable;
var columnsSet;
export default {
    data: () => ({
        mchtList: [],
        item: {},
        columnsSet: [],
        htmlEdit: true,
        htmlContent: "",
        seeText: false,
        // columnContent:[
        //     {
        //         title: "文章内容",
        //         data: "docContent",
        //         readonly:true
        //     }
        // ],
        checkboxValue: [],
        columnsReviseSet: [{
            title: "商户号",
            data: "mchtId",
            className: "operate"
        }, {
            title: "商户名称",
            data: "mchtNames",
            edit: true,
            readonly: true,
            className: "operate"
        }, {
            title: "文章号",
            data: "docId",
            edit: true,
            readonly: true,
            className: "operate"
        }, {
            title: "文章封面",
            data: "picUrl",
            width: "15%",
            img: true,
            upload: true
        }, {
            title: "文章标题",
            data: "docTitle",
            edit: true,
            className: "operate"
                // upload:false,
        },{
            title: "文章作者",
            data: "docAuthor",
            edit: true
        }, {
            title: "文章描述",
            data: "docDesc",
            textarea: true
        }, {
            title: "文章内容",
            data: "docContent",
        }]
    }),
    methods: {
        //还原弹出框位置
        resetBindDrag() {
            // this.$refs.modal._resetBindDrag();
            let notePopoverNone = document.getElementsByClassName('note-popover popover in note-link-popover bottom')
            for (let i = 0; i < notePopoverNone.length; i++) {
                notePopoverNone[i].style.display = "none"
            }
        },
        //查询按钮
        search: function() {
            dataTable.ajax.reload();
        },
        //重置按钮
        reset: function() {
            $(".form-inline")[0].reset();
            dataTable.ajax.reload();
        },
        getMcht(data) {
            let self = this;
            var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
            self.$post({
                url: "/api/v2" + projectName_Url + "/list/mcht/" + mchtId,
                method: "GET"
            }).then(response => {
                let list = response.content.info;
                list.unshift({
                    key: "所有商户",
                    value: ""
                });
                self.$set("mchtList", list);
                self.mchtIdValue = list[0].value
            }, error => {});
        },
        async sumbit() {
            if (!$(this.$els.reviseMform).valid()) {
                return false
            }
            //             if(this.item.docType == 0 && (!this.htmlContent || this.$refs.note.placeholder == "3000")){
            //                 Midway.alert({title:"温馨提示",content:"文章内容不能为空"})
            //                 return
            //             }
            //             if(this.$refs.note.placeholder <= 0){
            //                 Midway.alert({title:"温馨提示",content:"文章内容超出字数限制"})
            //                 return
            //             }
            //             let formData = new FormData(this.$els.reviseMform)
            //             formData.append("docId",this.item.docId)
            //             if(this.item.docType == 0){
            //                 formData.append("docContent",this.htmlContent)
            //             }
            //             if(formData.delete){
            //                 formData.delete("checkbox")
            //             }
            //             formData.append("state",this.item.state)
            //             let length = (eval(this.checkboxValue.join('+')) + "").length;
            //             let deployAgent;
            //             switch(length){
            //                 case 1:
            //                     deployAgent = "0000" + eval(this.checkboxValue.join('+'));
            //                     break;
            //                 case 2:
            //                     deployAgent = "000" + eval(this.checkboxValue.join('+'));
            //                     break;
            //                 case 3:
            //                     deployAgent = "00" + eval(this.checkboxValue.join('+'));
            //                     break;
            //                 default :
            //                     deployAgent = "00000";
            //             }
            ////             formData.append("deployAgent",deployAgent)
            //              await this.$postFormData({
            //                  url: "/api/v1" + projectName_Url + "/app/dep/upd.html",
            //                  data: formData
            //              });
            //             Midway.alert({title:"操作成功",content:"修改操作成功"})
            var form = this.$els.reviseMform;
            let formData = new FormData(form)
            formData.append("mchtId", this.item.mchtId);
            formData.append("docContent", this.htmlContent);
            console.log(this.htmlContent)
            var result = await this.$post({
                url: "/api/v1" + projectName_Url + "/plat/doc/" + this.item.docId,
                data: formData,
                method: "post"
            });
            Midway.alert({
                title: "操作提示",
                content: result.errorInfo
            })
            dataTable.ajax.reload(null, false);
            $(this.$els.reviseModal).modal('hide');
            this.resetBindDrag()
        }
    },
    components: {
        "html-edit": summernote
    },
    created() {
        columnsSet = [{
                title: "商户号",
                data: "mchtId",
                visible: false,
                className: "operate",
                width: "5%",
            }, {
                title: "商户名称",
                data: "mchtNames",
                edit: true,
                className: "operate"
            }, {
                title: "文章号",
                data: "docId",
                edit: true,
                width: "8%",
                className: "operate"
            }, {
                title: "文章标题",
                data: "docTitle",
                className: "operate",
                // upload:false,
                width: "9%",
               className:'wrap'
            }, {
                title: "文章封面",
                data: "picUrl",
                className: "operate",
                width: "9%",
                render: function(data) {
                        return `<img src=` + data + ` class="table-avatar" >`
                    }
                    // render: (value,type,row) => {
                    //     if(row.picUrl && row.flag != 6){
                    //         return `<img class="table-avatar" src=`+ row.picUrl + `>`
                    //     }else{
                    //         return ""
                    //     }
                    // }
            }, {
                title: "发现类型",
                data: "docType",
                width: "9%",
                className: "operate"
            },
            //             {
            //                 title: "文章内容",
            //                 data: "docContent",
            //                 htmlEdit:true,
            //                 className: "operate",
            //                 width: "9%"
            //             },
            {
                title: "文章作者",
                data: "docAuthor",
                edit: true,
                className: "operate",
                width: "9%",
                className:'wrap'
            },
            // {
            //     title: "文章描述",
            //     data: "docDesc",
            //     textarea: true,
            //     className: "operate",
            //     width: "9%"
            // },
            {
                title: "相关状态",
                data: "state",
                width: "9%",
                options: [{
                    key: "正常",
                    value: "0"
                }, {
                    key: "关闭",
                    value: "1"
                }],
                className: "operate",
                render: function(data) {
                        return (data == "0") ? "正常" : "关闭"
                    }
                    // render:value => {
                    //     if(value){
                    //         return [{key: "新用户安装指南",value: "1"},
                    //         {key: "其它业务流程",value: "2"},
                    //         {key: "燃气安装常识",value: "3"},
                    //         {key: "燃气价格",value: "4"},
                    //         {key: "公司简介",value: "5"},
                    //         {key: "企业文化",value: "6"}].find(data => data.value == value).key
                    //     }else{
                    //         return value
                    //     }
                    // }
            }, {
                title: "访问总数",
                data: "visitCount",
                edit: true,
                width: "9%",
                className: "operate"
                    // options:[
                    //     {key: "新闻",value: "0"},
                    //     {key: "通知",value: "1"},
                    //     {key: "贴士",value: "2"},
                    //     {key: "问题（有标题）",value: "3"},
                    //     {key: "问题（无标题）",value: "4"},
                    //     {key: "关于（有封面）",value: "5"},
                    //     {key: "关于（无封面）",value: "6"}
                    // ],
                    // render:value => ["新闻","通知","贴士","问题（有标题）","问题（无标题）","关于（有封面）","关于（无封面）"][value]
            }, {
                title: "创建时间",
                data: "mcreTime",
                width: "9%",
                dateTime: true,
                className: "operate",
                render: function(data) {
                        return dateFormat(data)
                    }
                    //     checkboxOptions:[
                    //         {key: "app", value: "1"},
                    //         {key: "web", value: "10"},
                    //         {key: "微信", value: "100"}
                    //     ],
                    //     render:(value,type,row) => ({"0":"","1":"app", "10": "web", "100": "微信","11": "app,web","101": "app,微信","110": "web,微信","111": "app,web,微信"})[+row.deployAgent]
            }, {
                title: "相关操作",
                className: "operate",
                width: "10%",
                render: function(value, type, row) {
                    return `
                            <button type="button" class="btn btn-primary btn-sm revise">修改</button>
                            <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                            <button type="button" class="btn btn-defalt btn-sm detail">详情</button>

                        `
                }
            }
        ]
    },
    ready: async function() {
        // $('form').each(function () { if ($(this).data('validator')) $(this).data('validator').settings.ignore = ".note-editor *"; });

        dateTime({
            format: "yyyy-mm-dd",
            minView: "2",
            startDate: "",
            endDate: ""
        });
        this.$set("columnsSet", columnsSet);
        var self = this;
        self.getMcht();
        // dataTable = createDataTable({
        //     config:{
        //         table:this.$els.table,
        //         columns:this.columnsSet
        //     },
        //     send:{
        //         url:"/api/v1" + projectName_Url + "/plat/banner/query"
        //         // searchData:{ docTitle:"docTitle", state: "state", docType:"type"}
        //     },
        //     receive:{
        //         list:"depList",
        //         total: "total"
        //     }
        // })

        dataTable = $(this.$els.table).DataTable({
            "columns": this.columnsSet, //定义列
            "ajax": async function(data, callback, settings) {
                var page = [{
                    "name": "iDisplayStart",
                    "value": 1 + data.start / data.length
                }, {
                    "name": "iDisplayLength",
                    "value": data.length
                }];
                //表单序列化数据
                var _data = serialize(self.$els.form, {
                    hash: true,
                    disabled: true,
                    empty: true
                });
                _data.aoData = JSON.stringify(page);

                //对开始结束时间进行数据处理
                _data.beginDate = _data.beginDate.replace(/-/g, "");
                _data.endDate = _data.endDate.replace(/-/g, "");
                //判断日期
                if(_data.beginDate.length>0 && _data.endDate.length>0){
                    if(_data.beginDate-_data.endDate > 0){
                        Midway.alert({title: "操作提示", content: '开始时间不能大于结束时间'})
                        // return false
                    }
                }else if(_data.beginDate.length>0 && _data.endDate.length <=0){
                    Midway.alert({title: "操作提示", content: '结束时间不能为空'})
                    // return false
                }else if(_data.beginDate.length <= 0 && _data.endDate.length > 0){
                    Midway.alert({title: "操作提示", content: '开始时间不能为空'})
                    // return false
                }
                //发送请求
                var result = await self.$post({
                    url: "/api/v1" + projectName_Url + "/plat/doc/query",
                    data: _data,
                    method: "POST"
                })
                if (result.respCode != "00") {
                    Midway.alert({
                        title: "操作失败",
                        content: result.content
                    })
                }
                callback({
                    recordsTotal: result.content.total,
                    recordsFiltered: result.content.total,
                    data: result.content.result || []
                })
            }
        });
        //隐藏列
        // dataTable.column(9).visible(false)

        $(self.$el).on("click", ".revise", function() {
            var Row = $(this).closest('tr').get(0);
            const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
            self.item = dataArray;
            self.$set("htmlContent", self.item.docContent);
            self.$nextTick(() => {
                    self.$refs.note.change()
                })
                //编辑框验证、保存、提交
            $(self.$els.reviseMform).validate(self.item.valdate = {
                async submitHandler() {

                },
                rules: {
                    docId: {
                        required: true
                    },
                    mchtId: {
                        required: true
                    },
                    docTitle: {
                        required: true,
                        stringMaxLength: 45
                    },
                    file: {
                        required: true
                    },
                    docType: {
                        required: true
                    },
                    docImg: {
                        required: true
                    },
                    docContent: {
                        required: true,
                        stringMaxLength: 3000,
                        stringCheck: true,
                        docContent: true
                    },
                    docAuthor: {
                        stringMaxLength: 45
                    },
                    docDesc: {
                        required:true,
                        stringMaxLength: 128
                    }
                },
                messages: {

                }
            });
            $(self.$els.reviseModal).modal('show');
        });

        $(self.$el).on("click", ".delete", async function() {
            var Row = $(this).closest('tr').get(0);
            var name = dataTable.row(Row).data().docTitle;
            var id = dataTable.row(Row).data().docId;

            await Midway.confirm({
                title: "删除文章",
                content: "是否要删除文章:" + name + "?"
            })
            var result = await self.$post({
                url: "/api/v1" + projectName_Url + "/plat/doc/" + id,
                data: {
                    docId: id
                },
                method: "DELETE"
            });
            Midway.alert({
                title: "操作提示",
                content: "删除成功"
            })
            dataTable.ajax.reload();
        });

        $(self.$el).on("click", ".state", async function() {
            var Row = $(this).closest('tr').get(0);
            var name = dataTable.row(Row).data().docTitle;
            var id = dataTable.row(Row).data().docId;
            let state = dataTable.row(Row).data().state == "0" ? 1 : 0
            await Midway.confirm({
                title: "修改状态",
                content: "是否确认要修改:" + name + "的状态?"
            })
            var result = await self.$post({
                url: "/api/v1" + projectName_Url + "/plat/doc/" + id,
                data: {
                    docId: id,
                    state: state
                }
            });
            dataTable.ajax.reload();
            Midway.alert({
                title: "修改状态",
                content: "状态修改成功"
            })
        });

        $(self.$el).on("click", ".detail", function() {
            var Row = $(this).closest('tr').get(0);
            const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
            dataArray.docContent = dataArray.docContent.replace(/(<([^>]+)>)/ig, "")
            document.getElementById('myTd').innerHTML = dataArray.docContent;
            dataArray.mcreTime = dateFormat(dataArray.mcreTime);
            self.item = dataArray;
            dateTime()
                //审核验证、保存、提交
            $(self.$els.detailMform).validate(self.item.valdate = {
                async submitHandler() {
                    var form = self.$els.detailMform;
                    var _data = serialize(form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    // return flase
                    await self.$post({
                        url: "/api/v1" + projectName_Url + "/plat/mcht/enterQuery",
                        data: _data,
                        method: "POST"
                    });
                    dataTable.ajax.reload(null, false);
                    $(self.$els.detailModal).modal('hide');
                    self.resetBindDrag()
                }
            });
            $(self.$els.detailModal).modal('show');
        });

        $(self.$el).on("click", ".htmlEdit", function() {
            var Row = $(this).closest('tr').get(0);
            var dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
            self.item = dataArray;
            self.$set("htmlContent", self.item.docContent || "")
            if (self.item.docType == "0") {
                self.$set("htmlEdit", true);
                self.$nextTick(() => {
                    self.$refs.seeNote.change()
                })
            } else {
                self.$set("htmlEdit", false);
            }
            $(self.$els.content).modal('show');
        })

    },
    beforeDestroy() {
        $(this.$el).off("click")
    }
}
</script>
